<template>
  <div class="redeem-code-management">
    <n-card title="兑换码管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <template #header-extra>
        <n-space>
          <n-button @click="handleBatchCreate">
            <template #icon>
              <icon-park-outline-add-computer />
            </template>
            批量生成
          </n-button>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-park-outline-add-one />
            </template>
            新增兑换码
          </n-button>
        </n-space>
      </template>

      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索兑换码"
            clearable
            class="w-200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.quota_type"
            placeholder="额度类型"
            clearable
            class="w-120px"
            :options="quotaTypeOptions"
          />
          <n-select
            v-model:value="searchParams.is_used"
            placeholder="使用状态"
            clearable
            class="w-120px"
            :options="usedStatusOptions"
          />
          <n-select
            v-model:value="searchParams.batch"
            placeholder="批次"
            clearable
            class="w-150px"
            :options="batchOptions"
            :loading="loadingBatches"
            @focus="fetchBatchList"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
        <n-space>
          <n-button @click="handleExport">
            <template #icon>
              <icon-park-outline-download />
            </template>
            导出兑换码
          </n-button>
        </n-space>
      </n-space>

      <!-- 统计卡片 -->
      <n-grid :cols="4" :x-gap="16" class="mb-16px">
        <n-grid-item>
          <n-statistic label="总兑换码数" :value="statistics.total" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="未使用" :value="statistics.unused" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="已使用" :value="statistics.used" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="已过期" :value="statistics.expired" />
        </n-grid-item>
      </n-grid>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        remote
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal v-model:show="modalVisible" preset="dialog" :title="modalTitle">
      <n-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-placement="left"
        label-width="120px"
        class="pr-20px"
      >

        <n-form-item label="额度类型" path="quota_type">
          <n-select
            v-model:value="formData.quota_type"
            placeholder="请选择额度类型"
            :options="quotaTypeOptions"
            @update:value="handleQuotaTypeChange"
          />
        </n-form-item>
        <n-form-item 
          v-if="formData.quota_type === 'domain'" 
          label="目标领域" 
          path="target_id"
        >
          <n-select
            v-model:value="formData.target_id"
            placeholder="请选择领域"
            :options="domainOptions"
          />
        </n-form-item>
        <n-form-item 
          v-if="formData.quota_type === 'expert'" 
          label="目标专家" 
          path="target_id"
        >
          <n-select
            v-model:value="formData.target_id"
            placeholder="请选择专家"
            :options="expertOptions"
          />
        </n-form-item>
        <n-form-item label="兑换次数" path="redeem_count">
          <n-input-number
            v-model:value="formData.redeem_count"
            :min="1"
            :max="1000"
            placeholder="可兑换的次数"
          />
        </n-form-item>
        <n-form-item label="批次标识" path="batch">
          <n-input
            v-model:value="formData.batch"
            placeholder="可选，用于批次管理"
            maxlength="50"
          />
        </n-form-item>
        <n-form-item label="过期时间" path="expires_at">
          <n-date-picker
            v-model:value="formData.expires_at"
            type="datetime"
            placeholder="选择过期时间（可选）"
            clearable
            class="w-full"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 批量生成弹窗 -->
    <n-modal v-model:show="batchModalVisible" preset="dialog" title="批量生成兑换码">
      <n-form
        ref="batchFormRef"
        :model="batchFormData"
        :rules="batchFormRules"
        label-placement="left"
        label-width="120px"
        class="pr-20px"
      >
        <n-form-item label="额度类型" path="quota_type">
          <n-select
            v-model:value="batchFormData.quota_type"
            placeholder="请选择额度类型"
            :options="quotaTypeOptions"
            @update:value="handleBatchQuotaTypeChange"
          />
        </n-form-item>
        <n-form-item 
          v-if="batchFormData.quota_type === 'domain'" 
          label="目标领域" 
          path="target_id"
        >
          <n-select
            v-model:value="batchFormData.target_id"
            placeholder="请选择领域"
            :options="domainOptions"
          />
        </n-form-item>
        <n-form-item 
          v-if="batchFormData.quota_type === 'expert'" 
          label="目标专家" 
          path="target_id"
        >
          <n-select
            v-model:value="batchFormData.target_id"
            placeholder="请选择专家"
            :options="expertOptions"
          />
        </n-form-item>
        <n-form-item label="兑换次数" path="redeem_count">
          <n-input-number 
            v-model:value="batchFormData.redeem_count" 
            :min="1" 
            :max="1000"
            placeholder="每个兑换码可兑换的次数" 
          />
        </n-form-item>
        <n-form-item label="生成数量" path="count">
          <n-input-number
            v-model:value="batchFormData.count"
            :min="1"
            :max="1000"
            placeholder="要生成的兑换码数量"
          />
        </n-form-item>
        <n-form-item label="批次标识" path="batch">
          <n-input
            v-model:value="batchFormData.batch"
            placeholder="可选，用于批次管理"
            maxlength="50"
          />
        </n-form-item>
        <n-form-item label="过期时间" path="expires_at">
          <n-date-picker
            v-model:value="batchFormData.expires_at"
            type="datetime"
            placeholder="选择过期时间（可选）"
            clearable
            class="w-full"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="batchModalVisible = false">取消</n-button>
          <n-button type="primary" :loading="batchSubmitLoading" @click="handleBatchSubmit">
            生成兑换码
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NTag, NSpace, useMessage, useDialog } from 'naive-ui'
import { redeemCodeApi, domainApi, expertApi } from '@/service/api/bizhi'
import { filterApiParams, filterFormData } from '@/utils/api'
import { formatTime } from '@/utils/time'

const message = useMessage()
const dialog = useDialog()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const batchSubmitLoading = ref(false)
const modalVisible = ref(false)
const batchModalVisible = ref(false)
const tableData = ref([])
const formRef = ref()
const batchFormRef = ref()
const domainOptions = ref([])
const expertOptions = ref([])
const batchOptions = ref([])
const loadingBatches = ref(false)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  quota_type: null,
  is_used: null,
  batch: null,
  page: 1,
  limit: 20
})

// 表单数据
const formData = reactive({
  id: null,
  quota_type: null,
  target_id: null,
  redeem_count: 1,
  batch: null,
  expires_at: null
})

// 批量生成表单数据
const batchFormData = reactive({
  quota_type: null,
  target_id: null,
  redeem_count: 1,
  count: 10,
  batch: null,
  expires_at: null
})

// 统计数据
const statistics = reactive({
  total: 0,
  unused: 0,
  used: 0,
  expired: 0
})

// 额度类型选项
const quotaTypeOptions = [
  { label: '通用额度', value: 'general' },
  { label: '领域额度', value: 'domain' },
  { label: '专家额度', value: 'expert' }
]

// 使用状态选项
const usedStatusOptions = [
  { label: '未使用', value: false },
  { label: '已使用', value: true }
]

// 表单验证规则
const formRules = {
  quota_type: [
    { required: true, message: '请选择额度类型', trigger: 'change' }
  ],
  target_id: [
    { 
      required: true, 
      message: '请选择目标', 
      trigger: 'change',
      validator: (rule: any, value: any) => {
        if (formData.quota_type !== 'general' && !value) {
          return new Error('请选择目标')
        }
        return true
      }
    }
  ],
  redeem_count: [
    { required: true, message: '请输入兑换次数', trigger: 'blur', type: 'number' }
  ]
}

// 批量生成表单验证规则
const batchFormRules = {
  quota_type: [
    { required: true, message: '请选择额度类型', trigger: 'change' }
  ],
  redeem_count: [
    { required: true, message: '请输入兑换次数', trigger: 'blur', type: 'number' }
  ],
  count: [
    { required: true, message: '请输入生成数量', trigger: 'blur', type: 'number' }
  ]
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 弹窗标题
const modalTitle = computed(() => {
  return formData.id ? '编辑兑换码' : '新增兑换码'
})

// 表格列配置
const columns: DataTableColumns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '兑换码', key: 'code', width: 150 },
  {
    title: '额度类型',
    key: 'quota_type',
    width: 100,
    render: (row: any) => {
      const typeMap = {
        general: '通用',
        domain: '领域',
        expert: '专家'
      }
      return h(NTag, {}, { default: () => typeMap[row.quota_type] || row.quota_type })
    }
  },
  { 
    title: '目标', 
    key: 'target', 
    width: 120,
    render: (row: any) => {
      // 根据额度类型明确显示目标
      switch (row.quota_type) {
        case 'general':
          return '通用'
        case 'domain':
          return row.domain?.name || '未知领域'
        case 'expert':
          return row.expert?.nickname || '未知专家'
        default:
          return '未知类型'
      }
    }
  },
  {
    title: '批次',
    key: 'batch',
    width: 150,
    render: (row: any) => {
      return row.batch || '-'
    }
  },
  { title: '兑换次数', key: 'redeem_count', width: 100 },
  {
    title: '使用状态',
    key: 'is_used',
    width: 100,
    render: (row: any) => {
      return h(NTag, {
        type: row.is_used ? 'success' : 'info'
      }, {
        default: () => row.is_used ? '已使用' : '未使用'
      })
    }
  },
  { title: '使用者', key: 'used_by_phone', width: 120 },
  {
    title: '使用时间',
    key: 'used_at',
    width: 180,
    render: (row: any) => formatTime(row.used_at)
  },
  {
    title: '过期时间',
    key: 'expires_at',
    width: 180,
    render: (row: any) => formatTime(row.expires_at)
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 180,
    render: (row: any) => formatTime(row.created_at)
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    render: (row: any) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, {
            size: 'small',
            type: 'primary',
            onClick: () => handleEdit(row)
          }, { default: () => '编辑' }),
          h(NButton, {
            size: 'small',
            type: 'error',
            disabled: row.is_used,
            onClick: () => handleDelete(row)
          }, { default: () => '删除' })
        ]
      })
    }
  }
]

// 获取选项数据
const fetchOptions = async () => {
  try {
    // 管理后台应该显示所有领域和专家，不仅仅是启用的
    const [domainResponse, expertResponse] = await Promise.all([
      domainApi.getDomainList({}),
      expertApi.getExpertList({})
    ])

    domainOptions.value = domainResponse.data.list.map((domain: any) => ({
      label: domain.name,
      value: domain.id
    }))

    expertOptions.value = expertResponse.data.list.map((expert: any) => ({
      label: expert.nickname,
      value: expert.id
    }))
  } catch (error) {
    console.error('获取选项数据失败:', error)
    message.error('获取选项数据失败')
    domainOptions.value = []
    expertOptions.value = []
  }
}

// 获取批次列表
const fetchBatchList = async () => {
  if (loadingBatches.value) return

  loadingBatches.value = true
  try {
    const response = await redeemCodeApi.getBatchList()
    batchOptions.value = (response.data || []).map((batch: string) => ({
      label: batch,
      value: batch
    }))
  } catch (error) {
    console.error('获取批次列表失败:', error)
    message.error('获取批次列表失败')
    batchOptions.value = []
  } finally {
    loadingBatches.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 从API获取统计数据
    const response = await redeemCodeApi.getRedeemCodeStats();
    if (response && response.data) {
      Object.assign(statistics, response.data);
    } else {
      message.error('获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    message.error('获取统计数据失败');
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await redeemCodeApi.getRedeemCodeList(filterApiParams(searchParams))
    tableData.value = response.data.list || []
    pagination.itemCount = response.data.pagination?.total || 0
  } catch (error) {
    console.error('获取兑换码数据失败:', error)
    message.error('获取数据失败')
    tableData.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 额度类型变化处理
const handleQuotaTypeChange = (value: string) => {
  formData.target_id = null
}

const handleBatchQuotaTypeChange = (value: string) => {
  batchFormData.target_id = null
}

// 新增
const handleAdd = () => {
  Object.assign(formData, {
    id: null,
    quota_type: null,
    target_id: null,
    redeem_count: 1,
    expires_at: null
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  Object.assign(formData, {
    ...row,
    expires_at: row.expires_at ? new Date(row.expires_at).getTime() : null
  })
  modalVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除兑换码"${row.code}"吗？删除后不可恢复。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await redeemCodeApi.deleteRedeemCode(row.id)
        message.success('删除成功')
        fetchData()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    }
  })
}

// 批量生成
const handleBatchCreate = () => {
  Object.assign(batchFormData, {
    quota_type: null,
    target_id: null,
    redeem_count: 1,
    count: 10,
    expires_at: null
  })
  batchModalVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    submitLoading.value = true

    if (formData.id) {
      // 兑换码通常不支持更新，这里可能需要根据实际业务调整
      message.warning('兑换码不支持修改')
    } else {
      // 过滤掉null值的表单数据
      const filteredData = filterFormData(formData)

      // 转换日期格式为ISO8601
      if (filteredData.expires_at) {
        filteredData.expires_at = new Date(filteredData.expires_at).toISOString()
      }

      await redeemCodeApi.createRedeemCode(filteredData)
      message.success('创建成功')
    }

    modalVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

// 批量提交
const handleBatchSubmit = async () => {
  try {
    await batchFormRef.value?.validate()
    
    batchSubmitLoading.value = true

    // 过滤掉null值的表单数据
    const filteredData = filterFormData(batchFormData)

    // 转换日期格式为ISO8601
    if (filteredData.expires_at) {
      filteredData.expires_at = new Date(filteredData.expires_at).toISOString()
    }

    await redeemCodeApi.batchCreateRedeemCode(filteredData)
    message.success(`成功生成${batchFormData.count}个兑换码`)

    batchModalVisible.value = false
    fetchData()
  } catch (error) {
    console.error('批量生成失败:', error)
    message.error('批量生成失败，请重试')
  } finally {
    batchSubmitLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  try {
    // TODO: 调用导出API
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    quota_type: null,
    is_used: null,
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

onMounted(async () => {
  try {
    console.log('兑换码页面开始加载')
    console.log('modalVisible:', modalVisible.value)
    console.log('batchModalVisible:', batchModalVisible.value)

    await fetchOptions()
    console.log('选项数据加载完成')

    await fetchStatistics()
    console.log('统计数据加载完成')

    await fetchData()
    console.log('表格数据加载完成')

    console.log('页面加载完成')
  } catch (error) {
    console.error('页面加载失败:', error)
  }
})
</script>

<style scoped>
.redeem-code-management {
  height: 100%;
}
</style>
